import {BaseCanvas} from "@/utils/BaseCanvas";
import {SHAPE_ID_JOIN_SYMBOL} from "@/utils/canvasUtil";
import {AndShape} from "@/utils/Drawing";

export class EventCanvas extends BaseCanvas {

  constructor(width: number, height: number) {
    const canvas = document.createElement('canvas')
    canvas.width = width
    canvas.height = height
    super(canvas, width, height)
  }

  pushShape(shape: AndShape) {
    if (this.ctx) {
      this.shapes.push(shape)
      shape.drawEventCanvas(this.ctx)
      this.revocationShapes = []
    }
  }

  clearDraw() {
    this.shapes = []
    this.clearRect()
  }

  reDraw() {
    this.clearRect()
    if (this.shapes.length) {
      for (const shape of this.shapes) {
        shape.drawEventCanvas(this.ctx)
      }
    }
  }

  click(event: MouseEvent) {
    const {x, y} = event
    const pixelAlpha = this.getUint8ClampedArray(x, y)
    const shapeId = pixelAlpha.join(SHAPE_ID_JOIN_SYMBOL)
    const shape = this.shapes.find(v => v.id === shapeId)

    if (shape) {
      console.log(shape)
      return new EventObj(event, shapeId, shape)
    }

  }

  /**
   * 直接获取点击位置像素点数据
   * https://www.cnblogs.com/hanshuai/p/14385286.html
   */
  getUint8ClampedArray(x: number, y: number) {
    const imageData = this.ctx.getImageData(x, y, 1, 1)
    // 只区前三个，最后的 alpha 值范围是 0-255 没有使用意义
    return Array.from(imageData.data).slice(0, 3)
  }

  /**
   * uint8ClampedArray 中所有像素点的值都存在一个一维数组中，存储的 rgba 值
   * 比如说两个像素 rgba(11,11,11,1)  rgba(234,112,101,0.2)
   * 在 uint8ClampedArray 存储的实际就是 [11,11,11,255,234,112,101,255]
   *
   * https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray
   */
  // getPixelAlpha(uint8ClampedArray: number[], x: number, y: number) {
  //     const startIndex = ((y - 1) * this.width + x) * 4
  //     return uint8ClampedArray.slice(startIndex, startIndex + 4)
  // }
}

export class EventObj {
  shapeId: string
  shape: AndShape
  event: MouseEvent

  constructor(event: MouseEvent, shapeId: string, shape: AndShape) {
    this.shapeId = shapeId
    this.shape = shape
    this.event = event
  }
}
